import { defineStore } from 'pinia'
import { COIN, WSS_URL } from '@/common/index.js'
import { postWalletApi, getUserInfoApi } from '@/api/userApi'
import { getWebSiteConfigApi } from '@/api/indexApi'
export const useMainStore = defineStore('mainStore', {
    state: () => {
        return {
            token: '',
            lang: 'en',
            isMobile: false,
            userInfo: {
                id: '',
                balance: 0, // 余额
            },
            ws: null,
            isConnect: false,
            dayMarket: {},
            klineMarket: {},
            webConfig: {}, // 网站信息
            btcClose: 0,
            etcClose: 0,
            usdtClose: 1,
            showLoading: false
        }
    },
    actions: {
        setToken(data = '') {
            this.token = data
            localStorage.setItem('token', data)
        },
        setLang(data = 'en') {
            this.lang = data
            localStorage.setItem('lang', data)
        },
        setMobile(data = false) {
            this.isMobile = data
        },
        setDayMarket(data = {}) {
            this.dayMarket = data
        },
        setKlineMarket(data = {}) {
            this.klineMarket = data
        },
        setLoading(data = false) {
            this.showLoading = data
        },
        // 获取用户余额
        async getUserBalance() {
            if(!this.token) return
             const res = await postWalletApi()
            this.userInfo.balance = res.legal_wallet.totle
        },
        // 获取用户信息
        async getUserInfoApi() {
            if(!this.token) return
            const res = await getUserInfoApi()
            this.userInfo.id = res.id
        },
        // 获取网站信息
        async getWebSiteConfig() {
            const res = await getWebSiteConfigApi()
            this.webConfig = res
        },
        onWss() {
            this.ws = new WebSocket(WSS_URL);
            this.ws.onopen = () => {
                console.log('WebSocket Connected');
                this.isConnect = true
                // 订阅一天
                this.onWebSocketSub(['daymarket'])
                //   订阅k线图
                this.onWebSocketSub([`kline.${COIN.name}/USDT`])
            };
            this.ws.onmessage = (event) => {
                let data = JSON.parse(event.data)
                switch(data.currency_name) {
                    case COIN.name:
                         // 一天的行情
                        if (data.type === "daymarket") {
                            this.setDayMarket(data)
                        }
                        else if (data.type === "kline") {
                            // k线图行情
                            this.setKlineMarket(data)
                        }
                    break;
                        case 'BTC':
                            if(data.type === "daymarket") {
                                this.btcClose = data.close
                            }
                    break;
                        case 'ETH':
                            if(data.type === "daymarket") {
                                this.ethClose = data.close
                            }
                           
                    break;
                }
            };
            this.ws.onerror = (error) => {
                console.error('WebSocket Error: ', error);
            };
            this.ws.onclose = () => {
                console.log('WebSocket Disconnected');
                if (!this.isConnect) {
                    // 重新连接
                    this.onWss()
                }
            };
        },
        //订阅
        onWebSocketSub(data = []) {
            for (let i = 0; i < data.length; i++) {
                // 多个订阅
                let param = {
                    event: "sub",
                    params: data[i]
                };
                this.ws.send(JSON.stringify(param))
                console.log('订阅成功:' + data[i])
            }
        },
        // 取消订阅
        onWebSocketUnSub(data = []) {
            for (let i = 0; i < data.length; i++) {
                // 多个订阅
                let param = {
                    event: "Unsub",
                    params: data[i]
                };
                this.ws.send(JSON.stringify(param))
                console.log('移除订阅:' + data[i])
            }
        }
    }
})